<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%String contextPath = request.getContextPath();%>
<html>
<head>
<meta charset="UTF-8">
<link href="http://g.alicdn.com/bui/bui/1.1.17/css/bs3/dpl.css" rel="stylesheet">
 <link href="http://g.alicdn.com/bui/bui/1.1.17/css/bs3/bui.css" rel="stylesheet">
<!-- ace styles -->
<%-- <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/ace.min.css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/ace-rtl.min.css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/ace-skins.min.css" /> --%>
<link href="${pageContext.request.contextPath}/resources/css/app.css" rel="stylesheet"/>
<style type="text/css">

 th.ui-th-column div{  
            white-space:normal !important;  
            height:auto !important;  
            padding:0px;  
            text-align: center;<!--让表头文字居中显示-->
}  
.ext-icon-key:{
	background: url('')
}
.content{
	border: 1px solid #c5d0dc;
	padding-left:5px;
	height:98%;
	padding-top:5px;
	overflow: visible;
}
.widget-body-toolbar{
padding-top:5px;
padding-left: 10px;
min-height: 42px;
border-bottom: 1px solid #c5d0dc;
background: #fafafa;
}
#filterInfo{
	border-top-style: none;
}
div#mytreepanel{
  padding-top: 6px;
  border: 1px solid #c3daf9;
  background: #f9f9f9;
  overflow: auto;
  min-height: 380px;
  height: 95px;
}
div#mytreepanel .bui-tree-list{
	border-style:none;
	background: none;
	padding-left: 8px;
}
.bui-context-menu .bui-menu-item-text{
	font-size: 12px;
	vertical-align: middle;
}
  .btns{
    margin-top: 20px;
  }
  .bui-select-list{
    overflow: auto;
  }
  .panel-header{
  	padding: 3px 3px;
  }
</style>
</head>
<body>
<div class="content">
	<div class="row">
		<!-- 部门管理 -->
		<div class="span6">
			<div class="panel panel-head-borded panel-small">
	          <div class="panel-header">部门管理</div>
	          <input id="filterInfo" type="text" style="width:203px;"  placeholder="您想查什么？">
	          <!--  <div class="button-group" style="margin: 3px 1px;">
			      <button class="button button">Left</button>
			      <button class="button button">Middle</button>
			      <button class="button button-danger">Right</button>
			    </div> -->
	          <div id="mytreepanel"></div>
	        </div>
	    </div>
	    <!-- 部门对应用户 -->
	    <div class="span22" id="userDiv">
	        <div class="panel panel-head-borded panel-small" style="padding-bottom: 5px;">
	          <div class="panel-header">用户列表
	          	 <input type="hidden" id="departmentId" name="department.id"/>
	          	 <span style="color:red;margin-left: 50px;font-weight: bold;font-size: 16px;">
		          	 <span id="departmentName" ></span>
		          	 <span id="departmentCode" style="margin-left: 20px;"></span>
		          	 <span id="departmentPhone" style="margin-left: 20px;"></span>
		          	 <span id="departmentManager" style="margin-left: 20px;"></span>
	          	 </span>
	          	<!-- <span id="departmentinfo" style="color:red; margin-left: 50px;font-weight: bold;font-size: 16px;"></span> -->
	          </div>
	          <div id="mygridpanel" style="padding-left: 5px;padding-top: 3px;padding-right: 5px;">
	          </div>
	        </div>
      	</div>
    </div>
</div>
<div id="departmentModal" style="display: none"> 
	<form class="form-vertical" id="departmentform">
		<input name="id" type="hidden" >
		<div class="control-group span8">
					<label class="control-label">上级机构：</label>
					<div class="controls">
						<input name="parent.id" type="hidden" >
						<input name="parent.name" type="text"  readonly="readonly" style="width: 120%;"/>
					</div>
		</div>
		<div class="control-group span8">
			<label class="control-label"><s>*</s>机构名称：</label>
			<div class="controls">
			<input name="name" type="text" class="control-text" style="width: 120%;" placeholder="机构名称(必填)" data-rules="{required : true}">
			</div>
		</div>
		<div class="control-group span8">
			<label class="control-label"><s>*</s>机构代码：</label>
			<div class="controls"><input name="code" type="text" class="control-text" style="width: 120%;" placeholder="机构代码(必填)" data-rules="{required : true}"></div>
		</div>
		<div class="control-group span8">
			<label class="control-label">机构电话：</label>
			<div class="controls"><input name="phone" type="text" class="control-text" style="width: 120%;" placeholder="机构电话"></div>
		</div>
		<div class="control-group span8">
			<label class="control-label">负责人：</label>
			<div class="controls">
				<select name="manager">
				</select>
			</div>
		</div>
	</form>
</div>
<div id="userModal" style="display: none;"> 
	<form class="form-horizontal" id="userForm" method="post">
		<input name="id" type="hidden" >
		<div class="row">
			<div class="control-group span8">
				<label class="control-label">机构：</label>
				<div class="controls">
					<input id="departmentTreeHidden" name="department.id" type="hidden" >
					<input id="departmentTree" name="department.name" type="text" class="input-normal control-text" readonly="readonly" data-rules="{required : true}"/>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="control-group span8">
				<label class="control-label"><s>*</s>用户名：</label>
				<div class="controls">
				<input name="username" type="text" class="input-normal control-text" placeholder="用户名(必填)" data-rules="{required : true}">
				</div>
			</div>
		</div>
		<div class="row">
			<div class="control-group span8">
				<label class="control-label"><s>*</s>姓名：</label>
				<div class="controls">
				<input name="nickname" type="text" class="input-normal control-text" placeholder="姓名(必填)" data-rules="{required : true}">
				</div>
			</div>
		</div>
		<div class="row">
			<div class="control-group span8">
				<label class="control-label">邮箱：</label>
				<div class="controls"><input name="email" type="text" class="input-normal control-text" placeholder="邮箱"></div>
			</div>
		</div>
		<div class="row">
			<div class="control-group span8">
				<label class="control-label">电话：</label>
				<div class="controls"><input name="phone" type="text" class="input-normal control-text" placeholder="联系电话"></div>
			</div>
		</div>
	</form>
</div>	

<div id="roleModal" style="display: none;">
<input type="hidden" name="id" id="userId">
<div class="row">
	<!-- <div class="span5">
		<div class="panel panel-head-borded panel-small">
			<div class="panel-header">已分配角色</div>
			<div id="authRoleList" class="span5"></div>
	     </div>
     </div> -->
    <div class="span5">
			<div class="panel panel-head-borded panel-small">
	          <div class="panel-header">已分配角色</div>
	          <div id="authRoleList" ></div>
	        </div>
	 </div>
	 <div class="span2">
		 <div class=" btns centered">
	        <button  class="button button-small" type="button" id="J_BtnRight">>></button><br>
	        <button  class="button button-small" type="button" id="J_BtnLeft"><<</button>
	      </div>
      </div>
     <div class="span5">
		<div class="panel panel-head-borded panel-small">
          <div class="panel-header">未分配角色</div>
          <div id="unauthRoleList" ></div>
        </div>
     </div>
</div>
</div>
		 <script src="${pageContext.request.contextPath}/resources/jslib/jquery-2.1.3.min.js"></script>
		  <script src="http://g.alicdn.com/bui/seajs/2.3.0/sea.js"></script>
		  <script src="http://g.alicdn.com/bui/bui/1.1.17/config.js"></script>
 
    <script type="text/javascript">
        BUI.use(['bui/tree',
                 'bui/extensions/treepicker',
                 'bui/menu','bui/data',
                 'bui/overlay',
                 'bui/form',
                 'bui/grid',
                 'bui/list'],function (Tree,TreePicker,Menu,Data,Overlay,Form,Grid,List) {
	      //树节点数据，
	      //text : 文本，
	      //id : 节点的id,
	      //leaf ：标示是否叶子节点，可以不提供，根据childern,是否为空判断
	      //expanded ： 是否默认展开
	    	//数据缓冲类
	  	      var departmentStore = new Data.TreeStore({
	  	    	  url:'<%=contextPath%>/department/findChildrens.action',
	  	    	  //autoLoad : true,
	  	    	  pidField : 'pid',
	  	          root : { //由于要显示根节点，所以需要配置根节点
	  	            id : 0,
	  	            text : '总部',
	  	            leaf:false
	  	          },
	  	          map : {
	  	              name : 'text',
	  	          }
	  	      });
	  	  	  //由于这个树，不显示根节点，所以可以不指定根节点
		      var tree = new Tree.TreeList({
		        render : '#mytreepanel',
		        dirCls : 'tree-dir',
		        showLine : true, //显示连接线
		        showRoot : true,//显示根节点
		        store : departmentStore,
		        loadMask:true
		      });
	  	  	  
     		 tree.render();
     		 //点击树结点
     		 tree.on('itemclick',function(ev){
 		        var item = ev.item;
 		        $('.log').text(item.text);
 		  	 });
     		 //树右键菜单
     		 tree.on('itemcontextmenu',function(ev){
	   	          var item = ev.item;
	   	          tree.setSelected(item);
	   	          menu.set('xy',[ev.pageX,ev.pageY]);
	   	          //为什么2次索引都是3呢?这是因为第一次删除的是分隔符，索引为3，而分隔符下面的“删除部门”原先索引为4，
	   	          //在删除分割符之后menu已经改变，“删除部门”的索引变为3了
	   	          menu.show();
	   	          return false; //prevent the default menu
   	        });
     		
     		 //添加部门
     		var addClick=function(){
	      		 menu.hide();
	      		 var selectItem=tree.getSelected();
	      		 var pnameField=form.getField("parent.name");
	      		pnameField.enable();
	      		$("#departmentform")[0].reset();
	      		form.action="<%=contextPath%>/department/add.action";
	      		 if(selectItem.id!==0)
	      			form.setFieldValue("parent.id",selectItem.id);
	      		form.setFieldValue("parent.name",selectItem.text);
	      		pnameField.disable();
	      		dialog.show();
	      	};
    	 	//编辑部门
	    	var editClick=function(){
	    		 menu.hide();
	    		 var selectItem=tree.getSelected();
	    		if(selectItem.id===0)
	    			BUI.Message.Alert('根节点不可编辑','error');
	    		else
	    		{
	    			form.action="<%=contextPath%>/department/update.action";
	    			var parentItem=tree.getItem(selectItem.pid);
	    			$("#departmentform")[0].reset();
	    			form.setFieldValue("id",selectItem.id);
	    			form.setFieldValue("name",selectItem.text);
	    			form.setFieldValue("code",selectItem.code);
	    			form.setFieldValue("phone",selectItem.phone);
	    			if(parentItem.id!==0)
		      			form.setFieldValue("parent.id",parentItem.id);
	    			form.setFieldValue("parent.name",parentItem.text);
	    			
		      		dialog.show();
	    		}
	        };
	    	//删除部门
	       var delClick=function(){
	    		menu.hide();
	    		var selectedItem=tree.getSelected();
	    		if(!selectedItem.leaf)
		        	BUI.Message.Alert('当前机构含有下级部门，不可删除','error');
	    		else
	    		{
	    			 BUI.Message.Confirm("确认要删除该机构吗?",function(){
	    				var del_id= selectedItem.id;
	    				$.ajax({
	    					url:'<%=contextPath%>/department/delete.action',
	    					data:{id:del_id},
	    					success:function(){
	    						//获得父级id
	    						var pid=selectedItem.pid;
	    						//获得父级结点
	    						var node=tree.getItem(pid);
	    						//刷新父级
	    						departmentStore.reloadNode(node);
	    					},
	    					error:function(){
	    						BUI.Message.Alert("删除机构["+selectedItem.text+"]失败,请重试或联系管理员","error");
	    					}
	    				})
	    			 })
	    		}
	        }; 
	        //右键菜单
	        var menu = new Menu.ContextMenu({
		          children : [
		            {
		              iconCls:' icon-plus',
		              text : '新增下级部门',
		              listeners:{
		                'click':addClick
		              }
		            },
		            {xclass:'menu-item-sparator'},
		            {
			              iconCls:'icon-pencil',
			              text : '编辑部门',
			              listeners:{
			                'click':editClick
			              }
			         },
		            {xclass:'menu-item-sparator'},
		            {
		              iconCls:'icon-remove',
		              text: '删除部门',
		              listeners:{
		            	  'click':delClick
		              }
		            }
		          ]
		       });
	        //添加或编辑部门弹出模态对话框
	     	var dialog = new Overlay.Dialog({
	            title:'机构信息',
	            width:400,
	            height:320,
	            closeAction : 'hide', 
	            //配置DOM容器的编号
	            contentId:'departmentModal',
	            success:function () {
	            	var param=form.serializeToObject();
	             	$.ajax({
	             		url:form.action,
	             		type:"POST",
	             		data:param,
	             		success:function(result){
	             			if(result.success)
	             			{
	             				var pid=param.pid;
	    						//获得父级结点
	    						var node=tree.getItem(pid);
	    						//刷新父级
	    						departmentStore.reloadNode(node);
	             				dialog.close();
	             			}
	             		},
	             		error:function(){
	             			BUI.Message.Alert("保存机构信息失败,请重试或联系管理员","error");
	             		}
	             	})
	            
	            }
	     	});
        	//模态对话框中的表单
       		var form = new Form.HForm({
                srcNode : '#departmentform',
            }).render();
        	
       	//添加或编辑部门弹出模态对话框
	     	var userEditing=new Grid.Plugins.DialogEditing({
	     		 contentId : 'userModal', //设置隐藏的Dialog内容
	             triggerCls : 'btn-edit', //触发显示Dialog的样式
	             editor : {
	            	 success:function(){
	            		 var editor=this,
	            		 form=editor.get('form'),
	            		 editType = userEditing.get('editType'),//add 或者 edit
	            		 url='<%=contextPath%>/user/saveOrUpdate.action';
	            		 form.valid();
	            		 if(form.isValid())
	            		 {
	                         form.ajaxSubmit({ //表单异步提交
	                           url : url,
	                           success : function(data){
	                             if(data.success)
	                             {
	                            	 editor.accept();
	                             }
	                             else
	                             {
	                            	 BUI.Message.alert("保存用户失败",'error');
	                             }
	                           },
	                           error:function(){
	      	            		 BUI.Message.alert("保存用户失败",'error');
	      	            	   }
	                         });
	                     }
	            	 }
	            	
	             }
	     	});	
       	
	     	userEditing.on('editorshow',function(ev){
	            var record = userEditing.get('record'); //type = ev.editType, //add ,edit
	            var userDiv=$("#userDiv");
	            var id=userDiv.find("#departmentId").val();
                var name=userDiv.find("#departmentName").text(); 
                picker.render();
            	$("#departmentTree").val(name);
            	picker.setSelectedValue(id);
	     		
	          });
          //用户列表表格
       	  var userStore = new Data.Store({
             url : '<%=contextPath%>/department/departmentUsers.action',
             pageSize : 10,
             root : 'datas',
             totalProperty : 'totalRecords',
             proxy : {//设置请求相关的参数
                 method : 'post',
                 //dataType : 'jsonp', //返回数据的类型
                 limitParam : 'pageSize', //一页多少条记录
                 pageIndexParam : 'currentPage', //页码
                 pageStart : 1
              }
           }),
           columns = [
			{title : '操作',width:150,elCls:'center',renderer:function(){
				return '<span class="grid-command btn-edit">编辑</span>&nbsp;&nbsp;&nbsp;<span class="grid-command role-edit">角色</span>';
			}},         
             {title : '用户名',dataIndex :'username',width:100,elCls:'center'}, 
             {title : '昵称',dataIndex :'nickname',width:150,elCls:'center'}, 
             {title : '邮箱',dataIndex : 'email',width:250,elCls:'center'},
             {title : '联系方式',dataIndex : 'phone',width:200,elCls:'center'}
           ],
           userGrid = new Grid.Grid({
             render:'#mygridpanel',
             idField:'id',
             columns : columns,
             height:250,
             forceFit : true,
             loadMask: true,
             store: userStore,
             plugins :[
				  userEditing,
                  Grid.Plugins.RowNumber,
                  Grid.Plugins.AutoFit,
                  Grid.Plugins.CheckSelection,
                  Grid.Plugins.ColumnResize
             ],
             tbar:{
            	 items:[
            	    { btnCls : 'button button-primary',
            	      text : '添加',
            	      listeners : {
                        'click' : addUser
                    }} ,
            	    { btnCls : 'button button-primary',text:'删除',listeners : {
                        'click' : delUsers
                    }},    
            	 ]
             },
             // 底部工具栏
             bbar:{
               // pagingBar:表明包含分页栏
               pagingBar:true
             },
             emptyDataTpl : '<div class="centered"><img alt="Crying" src="http://img03.taobaocdn.com/tps/i3/T1amCdXhXqXXXXXXXX-60-67.png"><h2>查询的数据不存在</h2></div>'
           });
       		
       		
	     	userGrid.render();
       
         tree.on('itemclick',function(ev){
             var node = ev.item;
             if(node.id===0)
            	 return;
          
             var userDiv=$("#userDiv");
             userDiv.find("#departmentId").val(node.id);
             userDiv.find("#departmentName").text(node.text);
             if(node.phone)
             	userDiv.find("#departmentPhone").text("电话："+node.phone);
             if(node.code)
            	 userDiv.find("#departmentCode").text("机构代码："+node.code);
             if(node.user)
            	 userDiv.find("#departmentManager").text("负责人："+node.user);
            	 
               //加载对应的数据，同时将分页回复到第一页
               userStore.load({id : node.id});
           });
         
         var departmentTree = new Tree.TreeList({
             store : departmentStore,
             //dirSelectable : false,//阻止树节点选中
             showLine : true //显示连接线
           });
         var  picker = new TreePicker({
             trigger : '#departmentTree',  
             valueField : '#departmentTreeHidden', //如果需要列表返回的value，放在隐藏域，那么指定隐藏域
             width:150,  //指定宽度
             children : [departmentTree] //配置picker内的列表
           });
      
         
         
            function addUser(){
	     		userEditing.add({}); 
            }
            
            function delUsers(){
            	BUI.Message.Confirm('确认要删除吗？',function(){
            		var selections = userGrid.getSelection();
            		var delIds="",len=selections.length;
            		for(var i=0;i<len;i++)
            		{
            			delIds+=selections[i].id;
            			if(i<len-1)
            				delIds+=",";
            				
            		}
            		$.ajax({
            			url:'<%=contextPath%>/user/deletes.action',
            			data:{'userIds':delIds},
            			success:function(data){
            				if(data.success){
            					userStore.remove(selections);
            					BUI.Message.Show({
            						msg:'删除用户成功',
            						icon:'success',
            						buttons : [],
            				        autoHide : true,
            				        autoHideDelay : 1000
            					});
            				}
            				else
            				{
            					BUI.Message.Alert("删除用户失败，请重试或联系管理员","error");
            				}
            			},
            			error:function(){
            				BUI.Message.Alert("删除用户失败，请重试或联系管理员","error");
            			}
            		})
            		
                },'question');
            }
          
            //用户角色分配
            var  authRoleList = new List.Listbox({
                elCls:'bui-select-list',//默认是'bui-simple-list'
                render : '#authRoleList',
                height : 170,
                idField:'id'
              }),
              unauthRoleList = new List.Listbox({
                elCls:'bui-select-list',//默认是'bui-simple-list'
                render : '#unauthRoleList',
                height : 170,
                idField:'id'
              });
           
            $('#J_BtnRight').on('click',function(){
                var selections1 = authRoleList.getSelection();
                authRoleList.removeItems(selections1);
                unauthRoleList.addItems(selections1);
              });
            $('#J_BtnLeft').on('click',function(){
                var selections2 = unauthRoleList.getSelection();
                unauthRoleList.removeItems(selections2);
                authRoleList.addItems(selections2);
            });
            authRoleList.on('dblclick',function(ev){
                  var element = $(ev.domTarget).closest('li'),
                      item = authRoleList.getItemByElement(element);
                  	  authRoleList.removeItem(item);
                  	  unauthRoleList.addItem(item);
             });
            unauthRoleList.on('dblclick',function(ev){
                  var element = $(ev.domTarget).closest('li'),
                      item = unauthRoleList.getItemByElement(element);
                  	  unauthRoleList.removeItem(item);
                  	  authRoleList.addItem(item);
            });   
         
            userGrid.on('itemclick',function (ev) {
                var item = ev.item,
                  sender = $(ev.domTarget);
	                if(sender.hasClass('role-edit')){
	                  editRole(item);
	                }
            });
            var userId;
            var roleDialog = new Overlay.Dialog({
                title:'分配角色',
                width:500,
                height:300,
                contentId:'roleModal',
                success:function () {
                	var items=authRoleList.getItems(),
                		roleIds="";
                	for(var i=0;i<items.length;i++)
                	{
                		roleIds+=items[i].id;
                		if(i<items.length-1)
                			roleIds+=",";
                	}
                	var param={
                			"id":userId,
                			"roleIds":roleIds
                	}
                	$.post("<%=contextPath%>/user/authUserRoles.action",param,function(data){
                		if(data.success)
                			roleDialog.close();
                		else
                			BUI.Message.Alert("分配角色失败","error");
                	})
                  
                }
              });
            
            function editRole(item)
            {
            	userId=item.id;
            	roleDialog.show();
            	$.getJSON("<%=contextPath%>/user/findRoles.action",{"id":userId},function(data){	
            		authRoleList.render();
                    unauthRoleList.render();
            		authRoleList.setItems(data.authedRoleList);
            		unauthRoleList.setItems(data.unauthedRoleList);
            	})
            }
    });
    </script>
</body>